package com.runmonk.core.study.Thread;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池测试类
 *
 * @author ：runmonk
 * @date ：Created in 2021/4/26 11:21
 */
public class ThreadPool {


    public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName("自建线程" + t.getId());
                return t;
            }
        };//线程工厂

        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();//拒绝策略
        LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<Runnable>(5);//工作队列
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1,
                6,
                0L,
                TimeUnit.MILLISECONDS,
                linkedBlockingQueue,
                threadFactory,
                handler);

        for (int i = 0; i < 50; i++) {
            if (i < 20) {
                MyTask myTask = new MyTask(i);
                Future future = executor.submit(myTask);
                try {
//                    System.out.println("线程执行返回的结果" + future.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("线程池中线程数目：" + executor.getPoolSize() + "，队列中等待执行的任务数目：" +
                    executor.getQueue().size() + "，已执行玩别的任务数目：" + executor.getCompletedTaskCount());
        }

        System.out.println("执行结束");
        executor.shutdown();
    }


}


class MyTask implements Callable {
    private int taskNum;

    public MyTask(int num) {
        this.taskNum = num;
    }


    @Override
    public Object call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "正在执行task " + taskNum);
        try {
            Thread.currentThread().sleep(4000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task " + taskNum + "执行完毕");
        return taskNum;
    }
}
